# -*- encoding: utf-8 -*-
import time
import wizard
import netsvc
import pooler
from osv import fields, osv
from tools.translate import _
from osv.orm import browse_record, browse_null
import datetime


def _aas_plan_exam(self, cr, uid, data, context):
	pool = pooler.get_pool(cr.dbname)
	if not context:
		context = {}
	list_obj = pool.get('aas.course.list')
	course_obj = pool.get('aas.course.course')
	year_obj = pool.get('aas.academic.year')
	ids = []
	if data.has_key('id'):
		id = data['id']
		list = list_obj.browse(cr, uid, id, context=context)
		for course in list.courses:
			ids.append(course.id)
	view_id = year_obj.get_view_id(cr, uid, 'aas_course', 'aas_course_course_tree_view_exam', context=context)
	result = {
        'domain': "[('id', 'in', " + str(ids) + ")]",
        'view_type': 'form',
        'view_mode': 'tree,form',
        'res_model': 'aas.course.course',
        'search_view_id': False,
        'view_id': [view_id],
        'type': 'ir.actions.act_window'
	}
	return result


class wizard_aas_plan_exam(wizard.interface):
	states = {
		'init': {
			'actions': [],
			'result': {'type': 'action', 'action': _aas_plan_exam, 'state': 'end'}
		}
	}	
wizard_aas_plan_exam("aas.plan.exam")


def _aas_plan_timetable(self, cr, uid, data, context):
	pool = pooler.get_pool(cr.dbname)
	if not context:
		context = {}
	list_obj = pool.get('aas.course.list')
	course_obj = pool.get('aas.course.course')
	year_obj = pool.get('aas.academic.year')
	ids = []
	if data.has_key('id'):
		id = data['id']
		list = list_obj.browse(cr, uid, id, context=context)
		for course in list.courses:
			ids.append(course.id)
	view_id = year_obj.get_view_id(cr, uid, 'aas_course', 'aas_course_course_tree_view_timetable', context=context)
	result = {
        'domain': "[('id', 'in', " + str(ids) + ")]",
        'view_type': 'form',
        'view_mode': 'tree,form',
        'res_model': 'aas.course.course',
        'search_view_id': False,
        'view_id': [view_id],
        'type': 'ir.actions.act_window'
	}
	return result


class wizard_aas_plan_timetable(wizard.interface):
	states = {
		'init': {
			'actions': [],
			'result': {'type': 'action', 'action': _aas_plan_timetable, 'state': 'end'}
		}
	}	
wizard_aas_plan_timetable("aas.plan.timetable")



class aas_course_register(osv.osv_memory):
	_name = 'aas.course.register'
	_columns = {
		'name': fields.char('Course Code', size=64),
		'lecturer': fields.char('Lecturer', size=64),
		'subject': fields.char('Subject', size=64),
		'total_credit': fields.integer('Total Credit'),
		'day': fields.selection((('mon', _('Monday')),
                                 ('tue', _('Tuesday')),
                                 ('wed', _('Wednesday')),
                                 ('thu', _('Thursday')),
                                 ('fri', _('Friday')),
                                 ('sat', _('Saturday')),
                                 ('sun', _('Sunday')),), string='Day'),
		'periods_str': fields.char('Periods', size=64,), 
		'year': fields.many2one('aas.academic.year', string='Year'),
		'semester': fields.many2one('aas.academic.semester', string='Semester'),
	}
	_defaults = {
		'day': lambda *a: 'mon',
	}
aas_course_register()



class wizard_aas_course_register(wizard.interface):
	_form = '''
		<form string="Register Courses">
			<separator string="Are you sure you want to register these courses?" colspan="4"/>
			<newline/>
			<field name="courses" nolabel="1" colspan="4" string="Courses"/>
	    </form>
	'''
	
	_fields = {
		'courses': {'type': 'many2many', 'relation': 'aas.course.register', 'readonly': True, 'string': _('Courses')},
	}
	
	def check_able_to_register_course(self, cr, uid, course):
		return True
	
	
	def _init(self, cr, uid, data, context):
		res = {}
		print 'data:', data
		print 'context:', context
		ids = data['ids']
		self.courses_ids = []
		if ids:
			pool = pooler.get_pool(cr.dbname)
			course_obj = pool.get('aas.course.course')
			courses = course_obj.browse(cr, uid, ids, context=context)
			
			register_obj = pool.get('aas.course.register')
			all_registers = register_obj.search(cr, uid, [])
			register_obj.unlink(cr, uid, all_registers)
			
			all_courses = []
			
			for course in courses:
				if self.check_able_to_register_course(cr, uid, course):
					self.courses_ids.append(course.id)
					data = {
						'name': course.name,
						'lecturer': course.lec_id and course.lec_id.name or '',
						'subject': course.subject_id.name,
						'total_credit': course.total_credit,
						'day': course.day,
						'periods_str': course.periods_str,
						'year': course.academic_year.id,
						'semester': course.academic_semester.id,
					}
					new_course = register_obj.create(cr, uid, data, context=context)
					all_courses.append(new_course)
			
			res.update({'courses': all_courses})
		return res
	
	def _register_courses(self, cr, uid, data, context):
		if self.courses_ids:
			pool = pooler.get_pool(cr.dbname)
			course_student_obj = pool.get('aas.course.student')
			for id in self.courses_ids:
				data = {
					'course_id': id,
					'student_id': uid,
					'time_register': datetime.datetime.now(),
				}
				course_student_obj.create(cr, uid, data, context=context)
		return {}
		
	def _show_registered_courses(self, cr, uid, data, context={}):
	    value = {
            'view_type': 'form', 
            'view_mode': 'tree,form', 
            'res_model': data['model'],
            'res_id': data['id'],
            'type': 'ir.actions.act_window', 
            'target': 'current',
        }
	    return value
	   
	states = {
		'init': {
			'actions': [_init],
			'result': {'type': 'form', 'arch': _form, 'fields': _fields,'state': [('end', 'Cancel', 'gtk-cancel', True),
																				   ('register', 'Register', 'gtk-ok', True),]},
		},
		'register': {
			'actions': [_register_courses],
			'result': {'type': 'state', 'state': 'done'},
		},
		'done': {
            'actions': [],
            'result': {'type': 'action', 'action': _show_registered_courses, 'state': 'end'},
        },
	}	
wizard_aas_course_register("aas.course.register")